package com.gu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gu.entity.EduSubject;
import com.gu.entity.excel.ExcelSubjectData;
import com.boot.exception.DiyException;
import com.gu.service.EduSubjectService;

import java.util.Map;

/**
 * Description: easyExcel 监听器
 *
 * @Autor: Rolin
 * datetime: 05-20-16:14
 */
// 此监听器 文档中不允许 spring托管
public class ExcelListener extends AnalysisEventListener<ExcelSubjectData> {

    private EduSubjectService eduSubjectService ;

    public ExcelListener() {
    }

    public ExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    //1.验证一级目录是否重复：
    private EduSubject isExistFirstSubject(EduSubjectService eduSubjectService , String subjectName){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",subjectName);
        wrapper.eq("parent_id","0");
        EduSubject eduSubject = eduSubjectService.getOne(wrapper);
        return eduSubject ;
    }

    //2.验证二级目录是否重复
    private EduSubject isExistSecondSubject(EduSubjectService eduSubjectService,String subjectName,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",subjectName);
        wrapper.eq("parent_id",pid);
        EduSubject eduSubject = eduSubjectService.getOne(wrapper);
        return eduSubject ;
    }


    //逐行读取，逐行验证写入数据库
    @Override
    public void invoke(ExcelSubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null){
            throw new DiyException("444","读取Excel失败");
        }
        //先判断一级目录是否存在,不存在就保存，后判断二级目录是否存在，存在就不执行写入数据库操作
        EduSubject existFirstSubject = this.isExistFirstSubject(eduSubjectService, subjectData.getFirstSubjectName());
        if(existFirstSubject==null){
            EduSubject eduSubject = new EduSubject();
            eduSubject .setParentId("0");
            eduSubject .setTitle(subjectData.getFirstSubjectName());
            eduSubjectService.save(eduSubject);
        }else {
            String pid = existFirstSubject.getId();
            EduSubject existSecondSubject = this.isExistSecondSubject(eduSubjectService, subjectData.getSecondSubjectName(), pid);
            if (existSecondSubject==null){
                EduSubject eduSubject = new EduSubject();
                eduSubject.setTitle(subjectData.getSecondSubjectName());
                eduSubject.setParentId(pid);
                eduSubjectService.save(eduSubject);
            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        System.out.println("表头信息："+headMap);
    }
}
